/**
 * 
 */
package com.fox.webapp.service.impl;

import java.util.List;

import javax.annotation.PostConstruct;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.thymeleaf.util.ListUtils;

import com.fox.webapp.domain.SystemSetting;
import com.fox.webapp.persistent.SystemSettingRepository;
import com.fox.webapp.service.ISystemSettingService;
import com.fox.webapp.utils.Constant;

/**
 * @author yockii
 *
 */
@Service
public class SystemSettingService implements ISystemSettingService {

	@Autowired
	private SystemSettingRepository systemSettingRepository;
	
	@Override
	public List<SystemSetting> getAllSettings() {
		return (List<SystemSetting>) systemSettingRepository.findAll();
	}

	@Override
	public boolean updateSetting(SystemSetting setting) {
		SystemSetting ss = null;
		if(setting.getId() != null){
			ss = systemSettingRepository.findOne(setting.getId());
			if(!ss.getKey().equalsIgnoreCase(setting.getKey())){
				return false;
			}
		} else {
			ss = systemSettingRepository.findByKey(setting.getKey());
		}
		ss.setValue(setting.getValue());
		systemSettingRepository.save(ss);
		return true;
	}
	
	@PostConstruct
	public void insertDefaultSettings(){
		List<SystemSetting> ssList = (List<SystemSetting>) systemSettingRepository.findAll();
		if (ListUtils.isEmpty(ssList)) {
			SystemSetting ss = new SystemSetting(Constant.SYS_REFLEVEL, Constant.SYS_REFLEVEL_DEFAULT);
			systemSettingRepository.save(ss);
			//TODO 其他配置
			
			
		} else {
			SystemSetting ss = systemSettingRepository.findByKey(Constant.SYS_REFLEVEL);
			if(ss == null || !StringUtils.hasText(ss.getValue())){
				ss = new SystemSetting(Constant.SYS_REFLEVEL, Constant.SYS_REFLEVEL_DEFAULT);
				systemSettingRepository.save(ss);
			}
			//TODO 其他配置
			
			
		}
	}

}
